import axios from 'axios';
import { PAYPAL_CLIENT_ID, PAYPAL_CLIENT_SECRET } from '../config/env';

const paypalFetch = axios.create({
    baseURL: 'https://api-m.sandbox.paypal.com',
    headers: {
        'Content-Type': 'application/json',
    }
});

class PaypalService {
    async getToken() {
        const { data } = await paypalFetch.post('/v1/oauth2/token',
            { "grant_type": "client_credentials" },
            {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                auth: {
                    username: PAYPAL_CLIENT_ID,
                    password: PAYPAL_CLIENT_SECRET
                }
            });
        const { access_token = '' } = data || {};
        return access_token;
    }

    async createOrder() {
        const token = await this.getToken();
        const orderData = {
            purchase_units: [
                {
                    amount: {
                        value: "0.01",
                    }
                },
            ]
        };
        const { data } = await paypalFetch.post('/v2/checkout/orders', orderData, {
            headers: {
                'Authorization': `Bearer ${token}`
            },
        });
        return data;
    }

    async captureOrder(orderId: string) {
        const token = await this.getToken();
        const { data } = await paypalFetch.post(`/v2/checkout/orders/${orderId}/capture`, {}, {
            headers: {
                'Authorization': `Bearer ${token}`
            },
        });
        return data;
    }
}

export default new PaypalService();